<?php
namespace admin;

use controllers\BaseControllers;
use Gregwar\Captcha\CaptchaBuilder;
use models\BaseDoo;

class Login extends BaseControllers {

    protected $dataBase;
    public function __construct()
    {
        $this->dataBase = new BaseDoo();
        //如果已经登录了，就不能再到登录页面去了
        if(lh_login('admin')){
            $this->redirect('/admin/index');
        }
        parent::__construct();
    }

    //登录页面
    public function index(){
        $this->display('admin/login/index');
    }

    //验证码
    public function vocde(){
        $builder = new CaptchaBuilder();
        $builder->build();
        header('Content-type:image/jpeg');
        $_SESSION['vcode'] = strtoupper($builder->getPhrase());
        $builder->output();
    }

    //进行登录操作
    public function logindo(){
        if(strtoupper($_POST['vcode']) != $_SESSION['vcode']){
            $this->error('/admin/login','验证码输入错误');
            exit();
        }
        $phone = trim($_POST['phone']);

        $password = sha1(trim($_POST['password']));

        $supplier = $this->dataBase->get('supplier',['id','phone','company_name'],['phone'=>$phone,'password'=>$password]);

        if($supplier){
            $this->dataBase->update('supplier',['update_time'=>time()],['id'=>$supplier['id']]);
            $_SESSION = $supplier;
            //登录成功的时候，生成_token
            $_SESSION['admin_token'] = sha1($supplier['id'].$_SERVER['HTTP_HOST']);
            $this->success('/admin/index','登录成功');
        }else{
            $this->error('/admin/login','用户名或者密码错误');
        }
    }

    //退出登录
    public function loginout(){
        //将session进行清空
        $_SESSION = [];
        //当浏览器的cookie存在的时候   直接删除cookie
        if(isset($_COOKIE[session_name()])){
            setcookie(session_name(),'',time()-3600,'/');
        }
        session_destroy();
        if(empty($_SESSION)){
            $this->success('/admin/login','成功退出');
        }
    }
}